package com.ruoyi.radar.outer;

import Jama.Matrix;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONString;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.radar.cal.KeGridData;
import com.ruoyi.radar.cal.PointData;
import com.ruoyi.radar.cal.ThreadAllBaseStation;
import com.ruoyi.radar.common.CommonMethod;
import com.ruoyi.radar.common.CommonUtil;
import com.ruoyi.radar.domain.*;
import com.ruoyi.radar.domain.RadarSiloResult;
import com.ruoyi.radar.service.*;
import com.ruoyi.radar.service.impl.RadarSiloRealServiceImpl;
import com.ruoyi.radar.service.impl.RadarSiloServiceImpl;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.*;

@Component
@CrossOrigin
@RestController
@RequestMapping("/outInterface")
public class OuterMessage implements CommandLineRunner {

    @Value("${url.gansu}")
    private String url;

    @Autowired
    CommonMethod commonMethod;
    @Autowired
    CommonUtil commonUtil;
    @Autowired
    KeGridData keGridData;

    @Autowired
    RadarSiloConfService radarSiloConfService;
    @Autowired
    RadarSiloService radarSiloService;
    @Autowired
    RadarSiloResultService radarSiloResultService;
    @Autowired
    RadarSiloRealService radarSiloRealService;
    @Autowired
    RadarWarnService radarWarnService;
    @Autowired
    RadarWarnMessageService radarWarnMessageService;



    @Override
    public void run(String... args) throws Exception {
//        this.connectPushTcp();
//        this.updateIsOnline();
//        this.readFile();
    }

//    @Scheduled(cron = "*/20 * * * * ?")
    private void getRadarData(){

        try {
            Object token = commonMethod.getToken();

            HttpRequest request = HttpUtil.createGet(url+"/request?token="+token+"&action=1");

            HttpResponse response = request.execute();
            String body = response.body();

            JSONObject jsonObjectRes = JSONObject.parseObject(body);
            Object datas = jsonObjectRes.get("datas");
            JSONArray objects = JSONArray.parseArray(datas.toString());
            HashMap<String, Object> confParam = new HashMap<>();
            confParam.put("type",1);
            List<RadarSiloConf> radarSiloConfs = radarSiloConfService.selectSiloConfList(confParam);
            for(Object object : objects){
                if(object == null || "".equals(object.toString())) continue;
                JSONObject obj = JSONObject.parseObject(object.toString());
                //仓模
                RadarSiloConf radarSiloConf = new RadarSiloConf();
                RadarSilo radarSilo = new RadarSilo();
//            "ShapeTypeID": "1", //
//"TopWidth": "0.6", //上部宽度
//"TopLength": "0.6", //上部长度
//"TopHeight": "0.3", //上部高度
//"MiddleWidth": "1.2", //中部宽度
//"MiddleLength": "1.2", //中部长度
//"MiddleHeight": "1", //中部高度
//"BottomWidth": "0.16", //底部宽度
//"BottomLength": "0.16", //底部长度
//"BottomHeight": "0.12", //底部高度
                String siloInitId = "";
                String siloParam = "";
                float topWidth = Float.parseFloat(obj.get("TopWidth").toString());
                float topLength = Float.parseFloat(obj.get("TopLength").toString());
                float topHeight = Float.parseFloat(obj.get("TopHeight").toString());
                float middleWidth = Float.parseFloat(obj.get("MiddleWidth").toString());
                float middleLength = Float.parseFloat(obj.get("MiddleLength").toString());
                float middleHeight = Float.parseFloat(obj.get("MiddleHeight").toString());
                float bottomWidth = Float.parseFloat(obj.get("BottomWidth").toString());
                float bottomLength = Float.parseFloat(obj.get("BottomLength").toString());
                float bottomHeight = Float.parseFloat(obj.get("BottomHeight").toString());
                if("1".equals(obj.get("ShapeTypeID"))){
                    siloInitId = "[\"1\",\"1\",\"1\"]";
//                    float topMax = Math.max(topWidth, topLength);
//                    float middleMax = Math.max(middleWidth, middleLength);
//                    float bottomMax = Math.max(bottomWidth, bottomLength);
//                    float max1 = Math.max(topMax, middleMax);
//                    float max = Math.max(max1, bottomMax);
//                    siloParam = "[["+topWidth+","+topLength+","+topMax+","+topMax+","+topHeight+
//                            ","+((max-topMax)/2)+","+((max-topMax)/2)+","+(bottomHeight+middleHeight)+"],["
//                            +middleWidth+","+middleLength+","+middleMax+","+middleMax+","+middleHeight+
//                            ","+((max-middleMax)/2)+","+((max-middleMax)/2)+","+(bottomHeight)+"],["
//                            +bottomWidth+","+bottomLength+","+bottomMax+ ","+bottomMax+","+bottomHeight+
//                            ","+((max-bottomMax)/2)+","+((max-bottomMax)/2)+",0]]";

                    float topMax = Math.max(topWidth, middleWidth);
                    float middleMax = Math.max(middleWidth, middleWidth);
                    float bottomMax = Math.max(middleWidth, bottomWidth);
                    float max1 = Math.max(topMax, middleMax);
                    float max = Math.max(max1, bottomMax);
                    siloParam = "[["+topWidth+","+middleWidth+","+topMax+","+topMax+","+topHeight+
                            ","+((max-topMax)/2)+","+((max-topMax)/2)+","+(bottomHeight+middleHeight)+"],["
                            +middleWidth+","+middleWidth+","+middleMax+","+middleMax+","+middleHeight+
                            ","+((max-middleMax)/2)+","+((max-middleMax)/2)+","+(bottomHeight)+"],["
                            +middleWidth+","+bottomWidth+","+bottomMax+ ","+bottomMax+","+bottomHeight+
                            ","+((max-bottomMax)/2)+","+((max-bottomMax)/2)+",0]]";
                }else if("2".equals(obj.get("ShapeTypeID"))){
                    float tmWidthMax = Math.max(topWidth, middleWidth);
                    float mbWidthMax = Math.max(middleWidth, middleWidth);
                    float widthMax = Math.max(tmWidthMax, bottomWidth);
                    float tmLengthMax = Math.max(topLength, middleLength);
                    float mbLengthMax = Math.max(middleLength, bottomLength);
                    float lengthMax = Math.max(tmLengthMax, bottomLength);
                    siloInitId = "[\"5\",\"5\",\"6\",\"6\",\"5\",\"5\",\"6\",\"6\",\"5\",\"5\",\"6\",\"6\"]";
                    siloParam = "[["+topWidth+","+middleWidth+","+topHeight+","+topHeight+","+(tmLengthMax-topLength)/2+","+(tmLengthMax-middleLength)/2+",0,0,"+(widthMax-tmWidthMax)/2+","+(lengthMax-tmLengthMax)/2+","+(bottomHeight+middleHeight)+"],"
                            +"["+topWidth+","+middleWidth+","+topHeight+","+topHeight+","+(tmLengthMax-topLength)/2+","+(middleLength-tmLengthMax)/2+",0,0,"+(widthMax-tmWidthMax)/2+","+(tmLengthMax+(lengthMax-tmLengthMax)/2)+","+(bottomHeight+middleHeight)+"],"
                            +"["+topLength+","+middleLength+","+topHeight+","+topHeight+","+(tmWidthMax-topWidth)/2+","+(tmWidthMax-middleLength)/2+",0,0,"+(widthMax-tmWidthMax)/2+","+(lengthMax-tmLengthMax)/2+","+(bottomHeight+middleHeight)+"],"
                            +"["+topLength+","+middleLength+","+topHeight+","+topHeight+","+(topWidth-tmWidthMax)/2+","+(middleLength-tmWidthMax)/2+",0,0,"+(tmWidthMax+(widthMax-tmWidthMax)/2)+","+(lengthMax-tmLengthMax)/2+","+(bottomHeight+middleHeight)+"],"

                            +"["+middleWidth+","+middleWidth+","+middleHeight+","+middleHeight+","+(middleLength-middleLength)/2+","+(middleLength-middleLength)/2+",0,0,"+(widthMax-middleWidth)/2+","+(lengthMax-middleLength)/2+","+bottomHeight+"],"
                            +"["+middleWidth+","+middleWidth+","+middleHeight+","+middleHeight+","+(middleLength-middleLength)/2+","+(middleLength-middleLength)/2+",0,0,"+(widthMax-middleWidth)/2+","+(middleLength+(lengthMax-middleLength)/2)+","+bottomHeight+"],"
                            +"["+middleLength+","+middleLength+","+middleHeight+","+middleHeight+","+(middleWidth-middleWidth)/2+","+(middleWidth-middleWidth)/2+",0,0,"+(widthMax-middleWidth)/2+","+(lengthMax-middleLength)/2+","+bottomHeight+"],"
                            +"["+middleLength+","+middleLength+","+middleHeight+","+middleHeight+","+(middleWidth-middleWidth)/2+","+(middleWidth-middleWidth)/2+",0,0,"+(middleWidth+(widthMax-middleWidth)/2)+","+(lengthMax-middleLength)/2+","+bottomHeight+"],"

                            +"["+middleWidth+","+bottomWidth+","+bottomHeight+","+bottomHeight+","+(mbLengthMax-middleLength)/2+","+(mbLengthMax-bottomLength)/2+",0,0,"+(widthMax-mbWidthMax)/2+","+(lengthMax-mbLengthMax)/2+",0],"
                            +"["+middleWidth+","+bottomWidth+","+bottomHeight+","+bottomHeight+","+(middleLength-mbLengthMax)/2+","+(bottomLength-mbLengthMax)/2+",0,0,"+(widthMax-mbWidthMax)/2+","+(mbLengthMax+(lengthMax-mbLengthMax)/2)+",0],"
                            +"["+middleLength+","+bottomLength+","+bottomHeight+","+bottomHeight+","+(mbWidthMax-middleWidth)/2+","+(mbWidthMax-bottomWidth)/2+",0,0,"+(widthMax-mbWidthMax)/2+","+(lengthMax-mbLengthMax)/2+",0],"
                            +"["+middleLength+","+bottomLength+","+bottomHeight+","+bottomHeight+","+(middleWidth-mbWidthMax)/2+","+(bottomWidth-mbWidthMax)/2+",0,0,"+(mbWidthMax+(widthMax-mbWidthMax)/2)+","+(lengthMax-mbLengthMax)/2+",0],"

                            +"]";
                }

                for(RadarSiloConf radarSiloConfObj:radarSiloConfs){
                    if(radarSiloConfObj.getSiloParam().equals(siloParam)&&radarSiloConfObj.getSiloInitId().equals(siloInitId))
                        radarSilo.setSiloConfId(radarSiloConf.getSiloConfId());
                }
                if(radarSilo.getSiloStockId() == null) {
                    radarSiloConf.setSiloConfId(commonUtil.uuId());
                    radarSiloConf.setSiloConfName(obj.get("StockName")+"仓模");
                    radarSiloConf.setSiloInitId(siloInitId);
                    radarSiloConf.setSiloParam(siloParam);
                    radarSiloConf.setCreateTime(commonUtil.currentTime());
                    radarSiloConf.setUpdateTime(commonUtil.currentTime());

                    radarSilo.setSiloConfId(radarSiloConf.getSiloConfId());
                }

                //料仓
                radarSilo.setSiloStockId(Integer.parseInt(obj.get("StockID").toString()));
                radarSilo.setSiloStockName(obj.get("StockName").toString());
                radarSilo.setSiloMaterial(obj.get("Material").toString());
                radarSilo.setSiloDensity(obj.get("Density").toString());
                radarSilo.setSiloHeight(obj.get("StockHeight").toString());
                radarSilo.setCreateTime(commonUtil.currentTime());
                radarSilo.setUpdateTime(commonUtil.currentTime());
                boolean b = radarSiloService.updateById(radarSilo) || radarSiloService.save(radarSilo);
            }



//        HttpRequest request = HttpUtil.createGet(url+"/request?token="+token+"&action=2");



            HttpRequest request2 = HttpUtil.createGet(url+"/request?token="+token+"&action=2");
            HttpResponse response2 = request2.execute();
            String body2 = response2.body();

            JSONObject jsonObject = JSONObject.parseObject(body2);
            Object datas2 = jsonObject.get("datas");
            JSONArray objects2 = JSONArray.parseArray(datas2.toString());
            for(Object object : objects2){
                if(object == null || "".equals(object.toString())) continue;
                JSONObject obj = JSONObject.parseObject(object.toString());
                RadarSiloResult radarSiloResult = new RadarSiloResult();

                radarSiloResult.setResultId(commonUtil.uuId());
                radarSiloResult.setStockId(obj.get("StockID").toString());
                radarSiloResult.setTimeLong(obj.get("TimeLong").toString());
                radarSiloResult.setLinerLev(obj.get("LinerLev").toString());
                radarSiloResult.setLinerVol(obj.get("LinerVol").toString());
                radarSiloResult.setLinerWeigh(obj.get("LinerWeigh").toString());
                radarSiloResult.setPerLevel(obj.get("PerLevel").toString());
                radarSiloResult.setLinerMax(obj.get("LinerMax").toString());
                radarSiloResult.setLinerMin(obj.get("LinerMin").toString());
                radarSiloResult.setWarning(obj.get("Warning").toString());
                radarSiloResult.setWarningLevel(obj.get("WarningLevel").toString());
                radarSiloResult.setCreateTime(commonUtil.currentTime());

                radarSiloResultService.save(radarSiloResult);

                RadarSiloReal radarSiloReal = new RadarSiloReal();
                radarSiloReal.setStockId(obj.get("StockID").toString());
                radarSiloReal.setTimeLong(obj.get("TimeLong").toString());
                radarSiloReal.setLinerLev(obj.get("LinerLev").toString());
                radarSiloReal.setLinerVol(obj.get("LinerVol").toString());
                radarSiloReal.setLinerWeigh(obj.get("LinerWeigh").toString());
                radarSiloReal.setPerLevel(obj.get("PerLevel").toString());
                radarSiloReal.setLinerMax(obj.get("LinerMax").toString());
                radarSiloReal.setLinerMin(obj.get("LinerMin").toString());
                radarSiloReal.setWarning(obj.get("Warning").toString());
                radarSiloReal.setWarningLevel(obj.get("WarningLevel").toString());
                radarSiloReal.setCreateTime(radarSiloResult.getCreateTime());

                HttpRequest requestSur = HttpUtil.createGet(url+"/request?token="+token+"&action=3&stockid="+obj.get("StockID"));

                String bodySur = requestSur.execute().body();
//                System.out.println(">>>>>>>>>>>>>>>>>>>>"+bodySur);
                JSONObject surObject = JSONObject.parseObject(bodySur);
                Object surDatas = surObject.get("datas");
                JSONObject surArray = JSONObject.parseObject(surDatas.toString());
                radarSiloReal.setSiloSurface(surArray.get("surface").toString());

                boolean b = radarSiloRealService.updateById(radarSiloReal) || radarSiloRealService.save(radarSiloReal);


                //保存报警信息逻辑
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("radarStockId",obj.get("StockID").toString());
                List<RadarWarn> radarWarns = radarWarnService.selectWarnByStock(param);
                for(RadarWarn radarWarn : radarWarns){
                    double v = Double.parseDouble(obj.get(radarWarn.getWarnColumn()).toString());
                    if(v >=  Double.parseDouble(radarWarn.getWarnValue())){
                        RadarWarnMessage radarWarnMessage = new RadarWarnMessage();
                        radarWarnMessage.setWarnMessageId(commonUtil.uuId());
                        radarWarnMessage.setWarnId(radarWarn.getWarnId());
                        radarWarnMessage.setWarnResultValue(v+"");
                        radarWarnMessage.setCreateTime(commonUtil.currentTime());
                        radarWarnMessageService.save(radarWarnMessage);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }


//    @Scheduled(cron = "0 */10 * * * ?")
    private void updateIsOnline(){
        List<RadarSilo> list = radarSiloService.list();
        for(RadarSilo radarSilo : list){
            Date createTime = radarSilo.getCreateTime();
            Date now = new Date();
            long l = now.getTime() - createTime.getTime();
            long maxTime = 10*60*1000L;
            if(l >= maxTime){
                radarSilo.setIsOnline("0");
            }else{
                radarSilo.setIsOnline("1");
            }
            radarSiloService.updateById(radarSilo);

//            String result  = DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");

        }
    }


    @PostMapping("/resolvAsc")
    public AjaxResult readFile(@RequestBody HashMap<String,Object> param){
//        String filePath = "D:\\\\\\\\asctotxt\\\\\\\\方形.asc";
//        String rootDir = System.getProperty("user.dir");
//        String filename = "方形.asc";
//        String filePath = rootDir + File.separator + filename;
//        System.out.println(filePath);
//        if(param.get("filePath"))

//        List<double[]> newList = new ArrayList<>();
        try{
            List<double[]> convertedData = convertData(param.get("filePath").toString());
//            Double max = null;
//            Double min = null;
//            Double sum = 0.0;
//            Integer num = 0;
            RadarSiloReal radarSiloReal = new RadarSiloReal();
            radarSiloReal.setStockId(param.get("coal_yard_id").toString());
            ArrayList<double[]> newList = sortData(convertedData,radarSiloReal);
            radarSiloReal.setSiloSurface(JSONArray.toJSONString(newList));
            boolean b = radarSiloRealService.updateById(radarSiloReal) || radarSiloRealService.save(radarSiloReal);

//            boolean b = saveModel(newList,param,radarSiloReal);
            if(b) {
                return AjaxResult.success("保存成功");
            }else{
                return AjaxResult.error("保存失败");
            }
        }catch (Exception e){
            return AjaxResult.error("");
        }


    }


//    public boolean saveModel(List<double[]> data,HashMap<String,Object> param,RadarSiloReal radarSiloReal) {
//
////            RadarSilo radarSilo = new RadarSilo();
////        radarSilo.setSiloStockId(5);
////            radarSilo.setSiloStockName("方形");
////            radarSilo.setSiloMaterial("煤");
////            radarSilo.setSiloDensity("1");
////            radarSilo.setSiloHeight("45");
////        radarSilo.setCreateTime(commonUtil.currentTime());
////        radarSilo.setUpdateTime(commonUtil.currentTime());
////            boolean b = radarSiloService.updateById(radarSilo) || radarSiloService.save(radarSilo);
//
//
//            radarSiloReal.setStockId(param.get("coal_yard_id").toString());
////        radarSiloReal.setTimeLong(obj.get("TimeLong").toString());
////        radarSiloReal.setLinerLev((sum/num) +"");
//////        radarSiloReal.setLinerVol(obj.get("LinerVol").toString());
//////        radarSiloReal.setLinerWeigh(obj.get("LinerWeigh").toString());
//////        radarSiloReal.setPerLevel(obj.get("PerLevel").toString());
////        radarSiloReal.setLinerMax(max+"");
////        radarSiloReal.setLinerMin(min+"");
////        radarSiloReal.setWarning(obj.get("Warning").toString());
////        radarSiloReal.setWarningLevel(obj.get("WarningLevel").toString());
//
//
//            radarSiloReal.setSiloSurface(JSONArray.toJSONString(data));
//            boolean b1 = radarSiloRealService.updateById(radarSiloReal) || radarSiloRealService.save(radarSiloReal);
//
//        return b1;
//    }

    public List<double[]> convertData(String filePath) {
        List<double[]> convertedData = new ArrayList<>();

        try {
            URL url = new URL(filePath);
            URLConnection connection = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine())!= null) {
                String[] parts = line.split(" ");
                double x = Double.parseDouble(parts[0]);
                double y = Double.parseDouble(parts[1]);
                double z = Double.parseDouble(parts[2]);
                double[] convertedRow = {x, y, z};
                convertedData.add(convertedRow);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return convertedData;
    }

//

    public  ArrayList<double[]> sortData(List<double[]> data,RadarSiloReal radarSiloReal) throws InterruptedException {
        ThreadPoolExecutor executor = ThreadAllBaseStation.executor;
        CopyOnWriteArrayList<double[]> splitPointListRes = new CopyOnWriteArrayList<>();
//        try {
            DecimalFormat df = new DecimalFormat("#");
         ArrayList<double[]> newList = new ArrayList<>();

            int index = 0;
//        ArrayList<String> objects = new ArrayList<>();
            Set<String> objects = new HashSet<>();
            Double minx = null;
            Double maxx = null;
            Double miny = null;
            Double maxy = null;
            Double minz = null;
            Double maxz = null;
            Double sum = 0.0;
            Integer num = 0;
            for(int i = 0; i < data.size();i++){
//            double xi = Double.parseDouble(df.format(data.get(i)[0]));
//            double yi = Double.parseDouble(df.format(data.get(i)[1]));
                double zi = data.get(i)[2];
                if(minz == null || minz > zi) minz = zi;
                if(maxz == null || maxz < zi) maxz = zi;
                double xi = Math.round(data.get(i)[0]);
                double yi = Math.round(data.get(i)[1]);

                if(!objects.contains(xi+","+yi)){
                    sum+=zi;
                    num++;
//                    double zi = Math.round(data.get(i)[2]);
                    double[] dou = new double[]{xi, yi,zi};
                    if(minx == null || minx > xi) minx = xi;
                    if(maxx == null || maxx < xi) maxx = xi;
                    if(miny == null || miny > yi) miny = yi;
                    if(maxy == null || maxy < yi) maxy = yi;

                    newList.add(dou);
                    objects.add(xi+","+yi);
                    index++;
                }
            }
            radarSiloReal.setLinerMin(minz+"");
            radarSiloReal.setLinerMax(maxz+"");
            radarSiloReal.setLinerLev((sum/num)+"");
            radarSiloReal.setLinerVol((sum/num)*(maxx-minx)*(maxy-miny)+"");

            HashMap<Integer,ArrayList<Double>> doublexList = new HashMap<>();
            HashMap<Integer,ArrayList<Double>> doubleyList = new HashMap<>();
            HashMap<Integer,ArrayList<Double>> doublezList = new HashMap<>();
//        HashMap<Integer,ArrayList<Double>> hashMap = new HashMap();
            int split = 1;
            double step = 0.5;
            for(double[] d : newList){
                int floor = (int)Math.floor((d[0] - minx) / split);
//                System.out.println(doublexList.get(floor));
                if(doublexList.get(floor)==null){
                    ArrayList<Double> list1 = new ArrayList<>();
                    ArrayList<Double> list2 = new ArrayList<>();
                    ArrayList<Double> list3 = new ArrayList<>();
                    doublexList.put(floor,list1);
                    doubleyList.put(floor,list2);
                    doublezList.put(floor,list3);
                }
                doublexList.get(floor).add(d[0]);
                doubleyList.get(floor).add(d[1]);
                doublezList.get(floor).add(d[2]);


//                xNewArr[ind] = d[0];
//                yNewArr[ind] = d[1];
//                zNewArr[ind] = d[2];
            }

//            newList = new ArrayList<>();


//            CountDownLatch countDownLatch = new CountDownLatch(doublexList.size());
            CountDownLatch countDownLatch = new CountDownLatch((int)(maxx-minx));
//            for(int i = 0;i < doublexList.size();i++){
            for(int i = 0;i <= (maxx-minx);i++){
                double[] doublexArray = new double[doublexList.get(i)==null?1:doublexList.get(i).size()];
                double[] doubleyArray = new double[doubleyList.get(i)==null?1:doubleyList.get(i).size()];
                double[] doublezArray = new double[doublezList.get(i)==null?1:doublezList.get(i).size()];

                int startA = (int)(i*split+minx);
                int endA = (int)(((i+1)*split+minx)<maxx?((i+1)*split+minx):maxx);
                double[][] x2Arr = new double[(int) ((endA-startA)/step)][(int) ((maxy-miny)/step + 1)];
                double[][] y2Arr = new double[(int) ((endA-startA)/step)][(int) ((maxy-miny)/step + 1)];

                for(double a = startA;(i==(maxz-minz)?(a<=endA):(a<endA));a+=step){
                    for(double b = miny;b <= maxy;b+=step){
                        x2Arr[(int) ((a-startA)/step)][(int) ((b-miny)/step)] = a;
                        y2Arr[(int) ((a-startA)/step)][(int) ((b-miny)/step)] = b;
                    }
                }

                for (int j = 0;doublexList.get(i)!=null&&j < doublexList.get(i).size(); j++) {
                    doublexArray[j] = doublexList.get(i).get(j);
                    doubleyArray[j] = doubleyList.get(i).get(j);
                    doublezArray[j] = doublezList.get(i).get(j);
                };
                if(doublexList.get(i) == null){
                    doublexArray[0] = 0.0;
                    doubleyArray[0] = 0.0;
                    doublezArray[0] = minz;
                }
                Double finalMinx = minx;
                Double finalMiny = miny;
                executor.submit(()->{
                    double[][] doubles = keGridData.gridData(doublexArray, doubleyArray, doublezArray, x2Arr, y2Arr);
//                    double[][] doubles = realDoubles.get();
                    for(int a = 0;a<doubles.length;a++ ){
                        for(int j = 0;j < doubles[a].length;j++){
                            double[] dou = new double[]{x2Arr[a][j], y2Arr[a][j],doubles[a][j]};
                            splitPointListRes.add(dou);
                        }
                    }
                    countDownLatch.countDown();
                    return;
                });
            }
            countDownLatch.await();

//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            executor.shutdown();
//        }
        newList = new ArrayList<>(splitPointListRes);
        newList.sort((a, b) -> {

            if (a[1] < b[1]) {
                return -1;
            } else if (a[1] > b[1]) {
                return 1;
            } else {
                if (a[0] < b[0]) {
                    return -1;
                } else if (a[0] > b[0]) {
                    return 1;
                } else {
//                    data.remove(b);
                    return 0;
                }
            }
        });
        for (double[] item : newList) {
            double v = roundToTwoDecimals(item[2]);
            item[2] = v;
//            item[2] = v<0?0:v;
        }
//        newList.sort(Comparator.<double[]>comparingDouble(a -> roundToTwoDecimals(a[2]))
//                .thenComparingDouble(a -> roundToTwoDecimals(a[2])));
        return newList;
    }

    private double roundToTwoDecimals(double value) {
        return BigDecimal.valueOf(value)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }



//    @Scheduled(cron = "*/30 * * * * ?")
//    private void getStockSilo(){
//
//        Object token = commonMethod.getToken();
//
//        HttpRequest request = HttpUtil.createGet(url+"/request?token="+token+"&action=2");
//
//        try {
//            HttpResponse response = request.execute();
//            String body = response.body();
//
//            JSONObject jsonObject = JSONObject.parseObject(body);
//            Object datas = jsonObject.get("datas");
//            JSONArray objects = JSONArray.parseArray(datas.toString());
//            for(Object object : objects){
//                if(object == null || "".equals(object.toString())) continue;
//                JSONObject obj = JSONObject.parseObject(object.toString());
//                RadarSilo radarSilo = new RadarSilo();
//                radarSilo.setSiloStockId(obj.get("StockID").toString());
//                radarSilo.setSiloStockName(obj.get("StockName").toString());
//                radarSilo.setSiloMaterial(obj.get("Material").toString());
//                radarSilo.setSiloDensity(obj.get("Density").toString());
//                radarSilo.setCreateTime(commonUtil.currentTime());
//                radarSilo.setUpdateTime(commonUtil.currentTime());
//                boolean b = radarSiloService.updateById(radarSilo) || radarSiloService.save(radarSilo);
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }

}
